﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;

namespace rpncs {
    public class PersistSettings {
        
        private static  string PATH = System.IO.Path.Combine( "rpncalc", "settings.txt" );
        public static void init() {
            try {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
                    if (!store.DirectoryExists( "rpncalc" )) {
                        store.CreateDirectory( "rpncalc" );
                    }
                    if (!store.FileExists( PATH )) {
                        IsolatedStorageFileStream fs = store.CreateFile( PATH );
                        fs.Close();
                    }

                }
            }
            catch (IsolatedStorageException e) {
                System.Console.Error.WriteLine( "rpncs: " + e.Message );
            }
        }

        public static void saveSettings(Settings s) {

            try {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
                
                    using(
                        StreamWriter w = new StreamWriter(
                            store.OpenFile( PATH, System.IO.FileMode.Open, System.IO.FileAccess.Write )
                        ) ){
                            w.Write( s.getSettingsAsText().ToString() );
                            if (System.Diagnostics.Debugger.IsAttached) {
                                System.Console.Write( s.getSettingsAsText() );
                            }
                            w.Close();
                    }
                }
            }
            catch (IsolatedStorageException e) {
                System.Console.Error.WriteLine( "rpncs: " + e.Message );
            }
        }

        public static Boolean loadSettings( ref Settings s ) {
            StringBuilder sb = new StringBuilder();

            using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
                using (StreamReader r = new StreamReader( store.OpenFile( PATH, FileMode.Open, FileAccess.Read ) )) {
                    sb.Append( r.ReadToEnd() );
                    r.Close();
                }
            }

            if (sb.Length > 0) {
                string[] st = sb.ToString().Split( ';' );
                string pl = st[1].Split( '=' )[1];
                s.decimalPlaces = Int32.Parse( pl );
                return true;
            }
            return false;
        }
    }
}
